import React from 'react';
import { useState, useContext } from 'react';
import DataContext from './context/DataContext';
import api from './api/api';
import { ToastContainer, Toast } from 'react-bootstrap';
import EditDescription from './EditDescription';
import { useHistory, useParams } from 'react-router-dom/cjs/react-router-dom';


const PostEpisode = () => {

  const { id: podcastId } = useParams();
  const { loginUserId } = useContext(DataContext);
  const history = useHistory();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [toastShow, setToastShow] = useState(false);
  const [toastContent, setToastContent] = useState('');

  const handleSubmit = async () => {
    const body = { title, description };
    try {
      const response = await api.post(`podcasts/${podcastId}/episodes`, body);
      setToastContent("创建成功！");
      setTimeout(() => {
        history.push(`/users/${loginUserId}`);
      }, 2000);
    } catch (error) {
      setToastContent(`创建失败：${error.message}`);
    } finally {
      setToastShow(true);
      setTimeout(() => {
        setToastShow(false);
      }, 2000);
    }
  };

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container d-flex flex-column align-items-center">
        <h1 className='mt-2 mb-5'>创建单集</h1>
        <form className='mb-2' onSubmit={(e) => e.preventDefault()}>
          <div className="mb-3">
            <label for="title" className="form-label">单集名称</label>
            <input type="text" className="form-control" id="title" onChange={(e) => setTitle(e.target.value)} />
          </div>
          <div className='mb-3'>
            <label for="description" className="form-label">描述</label>
            <EditDescription description={description} setDescription={setDescription} />
          </div>
          <div className="text-center mb-4">
            <button type="submit" className="btn btn-primary" onClick={handleSubmit}>提交</button>
          </div>
        </form>
      </div>
      <ToastContainer position='middle-center' className='m-2'>
        <Toast show={toastShow} onClose={() => { setToastShow(false); }}>
          <Toast.Header>
            <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
            <strong className="me-auto">雨呓</strong>
          </Toast.Header>
          <Toast.Body>{toastContent}</Toast.Body>
        </Toast>
      </ToastContainer>
    </div>
  );
};

export default PostEpisode;
